/**
 * 
 */
package com.wubo.sec.core;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.wubo.common.web.JsonUtils;

/**
 * 用户验证失败处理器<br/>
 * @author WuBo
 * @CreateDate 2012-2-15
 */
public class UserAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {
	public final static String SPRING_SECURITY_LAST_USERNAME = "SPRING_SECURITY_LAST_USERNAME";
	public final static String SCRIPT_LOGIN_ACTION = "/scriptLogin.action";
	
	private boolean rememberUsername = true;
	private String scriptLoginAction = SCRIPT_LOGIN_ACTION;
	
	public UserAuthenticationFailureHandler(){
		super();
		super.setUseForward(true);
	}
	
	public UserAuthenticationFailureHandler(String defaultFailureUrl){
		super(defaultFailureUrl);
	}
	
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
		super.setDefaultFailureUrl(UserLoginPageHelper.getLoginFailureUrl(request));
		
		if(rememberUsername){
			rememberUsername(request);
		}
		
		if(UserLoginPageHelper.isScriptRequest(request)){
			request.setAttribute("Success", Boolean.FALSE);
			scriptLogin(request, response, exception);
		}else{
			super.onAuthenticationFailure(request, response, exception);
		}
	}
	
	public void scriptLogin(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception){
		String errorMsg = "";
		if(exception != null){
			errorMsg = exception.getMessage();
		}

		writeJsonError(UserLoginPageHelper.SCRIPT_LOGIN_ERROR, errorMsg, response);
	}
	
	protected void rememberUsername(HttpServletRequest request){
		String username = request.getParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
		request.setAttribute(SPRING_SECURITY_LAST_USERNAME, username);
	}

	public boolean isRememberUsername() {
		return rememberUsername;
	}

	public void setRememberUsername(boolean rememberUsername) {
		this.rememberUsername = rememberUsername;
	}

	public String getScriptLoginAction() {
		return scriptLoginAction;
	}

	public void setScriptLoginAction(String scriptLoginAction) {
		this.scriptLoginAction = scriptLoginAction;
	}

	private static void writeJsonError(String code, String error, HttpServletResponse response) {
		String json = null;
		if(code == null){
			json = "{\"success\":false, \"error\":\""+error+"\"}";
		}else{
			try{
				json = "{\"success\":false,\"data\":\""+code+"\",\"error\":\""+error+"\"}";
				JsonUtils.write(json, response.getOutputStream());
			}catch(Exception e){
				throw new RuntimeException("序列化对象【"+json+"】时出错", e);
			}
		}
	}
	
}
